import { ISelectParamUpdateOption, SelectParamService } from '@manycore/pages-vm-api';
import { ApiImpl } from 'message-lite';
import { defaultProductId } from '../../constant';
import { CustomModel } from '../../types';
import {
  getSelectedCustomModels,
  modelFilter,
  getSelectedElements,
  transformParamModelToParameters,
  unique,
} from '../../util';

@ApiImpl()
export class SelectParamServiceImpl extends SelectParamService {
  async getParameters() {
    const allSelectedModels = await getSelectedCustomModels(getSelectedElements());
    return transformParamModelToParameters(allSelectedModels);
  }

  /**
   * 更新模型数据
   * @param option
   */
  async updateParameters(option: ISelectParamUpdateOption): Promise<void> {
    const { fields } = option;
    const doorOption = IDP.Custom.DoorCoveringHardware.getOption();
    const selectedElements = getSelectedElements();
    // 当前被选中的模型
    const selectedIds = selectedElements.map((i) => i.id);
    const allSelectedModels = await getSelectedCustomModels(selectedElements);
    // 对模型进行去重
    const allSelectedModelsUnique = unique(
      allSelectedModels.map((i) => i.getRoot(true)),
      (i) => i.id
    );

    // 找到所有需要更新的模型
    const allNeedUpdateModels = modelFilter(
      allSelectedModelsUnique,
      (i) => {
        if (i.productId === defaultProductId) {
          if (doorOption.selectTarget === 'door') {
            return selectedIds.includes(i.getParent()?.id!);
          }
          return true;
        }
        return false;
      },
      7
    );

    const updateModel: CustomModel[] = [];

    allNeedUpdateModels.forEach((model) => {
      fields.forEach((field) => {
        if (model.hasParam(field.name)) {
          const param = model.getParam(field.name)!;

          if (param.getVisible()) {
            const value = param.getValue();
            if (value !== field.value) {
              param.setValue(field.value);
              updateModel.push(model.getRoot(true));
            }
          }
        }
      });
    });

    if (updateModel.length) {
      await IDP.Custom.Design.CustomModel.updateAsync({
        models: unique(updateModel),
      });
    }
  }
}
